/*
 *  Copyright (c) 2019-2020, Medvish
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kw.common.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kw.common.core.config.FilterIgnorePropertiesConfig;
import com.kw.common.security.annotation.IgnoreAuth;
import com.kw.common.security.util.HttpMethodUtil;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.io.IOException;
import java.util.Map;

/**
 * @author Medvish
 * @date 2019/03/08
 *
 * <p>
 * 1. 支持remoteTokenServices 负载均衡
 * 2. 支持 获取用户全部信息
 */
@Configuration

@Slf4j
public class PigResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
	@Autowired
	protected ResourceAuthExceptionEntryPoint resourceAuthExceptionEntryPoint;

	@Autowired
	private FilterIgnorePropertiesConfig ignorePropertiesConfig;
	@Autowired
	private AccessDeniedHandler pigAccessDeniedHandler;
	@Autowired
	private RestTemplate lbRestTemplate;

	@Autowired
	private ResourceServerProperties resourceServerProperties;


	@Autowired
	RequestMappingHandlerMapping requestMappingHandlerMapping;
	/**
	 * 默认的配置，对外暴露
	 *
	 * @param httpSecurity
	 */
	@Override
	@SneakyThrows
	public void configure(HttpSecurity httpSecurity) {
		//允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
		httpSecurity.headers().frameOptions().disable();
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>
			.ExpressionInterceptUrlRegistry registry = httpSecurity
			.authorizeRequests();
		//requestmappinghandlermapping 获得所有注解 放行
		requestMappingHandlerMapping.getHandlerMethods().entrySet().stream().forEach(s->{
			IgnoreAuth anno = s.getValue().getMethod().getAnnotation(IgnoreAuth.class);
			PatternsRequestCondition p = s.getKey().getPatternsCondition();
			p.getPatterns().stream().forEach(url->{
				if(anno != null){
					if(s.getKey().getMethodsCondition().getMethods().size()==0) {
						registry.antMatchers(url).permitAll();
					}else{
						HttpMethodUtil.transFromRequestMethod(s.getKey().getMethodsCondition().getMethods())
							.stream().forEach(m->{
							registry.antMatchers(m,url).permitAll();
						});
					}
				}
			});
		});
		ignorePropertiesConfig.getUrls()
			.forEach(url -> registry.antMatchers(url).permitAll());
		registry.anyRequest().authenticated()
			.and().csrf().disable();
	}



	@Bean
	public TokenStore jwtTokenStore() {
		return new JwtTokenStore(this.jwtAccessTokenConverter());
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
		resources.tokenStore(jwtTokenStore());
		resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint);
		resources.accessDeniedHandler(pigAccessDeniedHandler);
	}



	//
	@Bean
	protected JwtAccessTokenConverter jwtAccessTokenConverter() {
		JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
		DefaultAccessTokenConverter defaultConverter = new DefaultAccessTokenConverter();
		defaultConverter.setUserTokenConverter(new PigUserAuthenticationConverter());
		jwtAccessTokenConverter.setAccessTokenConverter(defaultConverter);
		String publicKey = getPubKey();
		jwtAccessTokenConverter.setVerifierKey(publicKey);
		return jwtAccessTokenConverter;
	}
	private String getPubKey() {
		//这里远程 也可以本地publickey
		return getKeyFromAuthorizationServer();
	}

	/**
	 * 通过访问授权服务器获取非对称加密公钥 Key
	 *
	 * @return 公钥 Key
	 */
	private String getKeyFromAuthorizationServer() {
		ObjectMapper objectMapper = new ObjectMapper();
		String pubKey = lbRestTemplate.getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class);
		try {
			Map map = objectMapper.readValue(pubKey, Map.class);
			return map.get("value").toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}



}
